package com.swift.monitor.core.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class CompanyUtil {
    /**
     * 带单位容量转为byte
     * 
     * @param str
     * @return
     */
    public static long parse(String str) {
        if (StringUtils.isEmpty(str)) {
            return 0;
        }
        str = str.toUpperCase();
        String regex = "([0-9]+)(K|M|G)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        if (!m.find()) {
            throw new IllegalArgumentException("不合法的值[" + str + "].");
        }
        long size = Long.parseLong(m.group(1));
        char unit = m.group(2).charAt(0);
        switch (unit) {
            case 'K':
                return size * 1024;
            case 'M':
                return size * 1024 * 1024;
            case 'G':
                return size * 1024 * 1024 * 1024;
            default:
                throw new IllegalArgumentException("未知容量[" + str + "].");
        }
    }

    /**
     * 转换为兆.
     * 
     * @param size
     * @return
     */
    public static long toMlong(long size) {
        return size / 1024 / 1024;
    }

    /**
     * 转换成带单位数值
     * 
     * @param size
     * @return
     */
    public static String toMstr(long size) {
        int count = 0;
        for (; size >= 1024;) {
            size = size / 1024;
            count++;
            if (count >= 2) {
                break;
            }
        }
        switch (count) {
            case 0:
                return size + "B";
            case 1:
                return size + "K";
            case 2:
                return size + "M";
            default:
                throw new IllegalArgumentException("不合法的值[" + count + "]");
        }

    }
}
